/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Validator;

import dao.HouseListDAO;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

/**
 *
 * @author amkreuz
 */
@FacesValidator("Validator.HouseNameValidator")
public class HouseNameValidator implements Validator {

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        try {
            HouseListDAO.init();

            List<SelectItem> hl = HouseListDAO.getHouseList();

            Iterator<SelectItem> i = hl.iterator();
            boolean noThrow = true;
            while (i.hasNext() && noThrow) {
                SelectItem sl = i.next();
                if (sl.getValue().toString().equals(value.toString())) {
                    noThrow = false;
                }
            }
            if (!noThrow) {
                FacesMessage msg = new FacesMessage("Household Already Exists");
                throw new ValidatorException(msg);
            }

        } catch (SQLException ex) {
            Logger.getLogger(JoinHouseholdValidator.class.getName()).log(Level.SEVERE, null, ex);
            FacesMessage msg = new FacesMessage("Error in System");
            throw new ValidatorException(msg);
        } finally {
            try {
                HouseListDAO.terminate();
            } catch (SQLException ex) {
                Logger.getLogger(JoinHouseholdValidator.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
